/*
   This acts as a mixin to place widgets based off of noBuisnessBase/form/WidgetBase into a real dijit/Form
*/


define(
   [
      'dojo/_base/declare',
      'dojo/_base/lang',
      'dojo/Evented',
      'dojo/dom-construct',
      'dijit/form/Form'
   ],
   function(declare, lang, evented, domConstruct, Form)
   {
      return declare([Form, evented],
      {
         mAutoPublish: true,
         enctype: 'multipart/form-data',
         postscript: function(args){
            this.inherited(arguments);
            
            args.pWidget.setForm(this);
            domConstruct.place(args.pWidget.domNode, this.domNode, "only");
            this.mSignal = dojo.connect(this, "onSubmit", function(pEvent){
               dojo.stopEvent(pEvent);
               if(this.validate())
               {
                  if(args.pWidget.emitFormExecuted)
                  {
                     if(!args.pWidget.mEmitted)
                        args.pWidget.mEmitted = args.pWidget.emitFormExecuted();
                  }
                  else
                     args.pWidget.submitForm();
               }
               else
                  // put this in a tiemout so that any dojox busy buttons in the from can be snapped back to non busy state in the postSubmit call
                  setTimeout(lang.hitch(args.pWidget, "postSubmit", {}, true), 1);
               
            });

            this.own(args.pWidget.on("formExecuted", lang.hitch(this, function(data){
                  if(this.mAutoPublish)
                     dojo.publish("global:AjaxResult", [data]);
               
                  this.emit("formExecuted", data);
               })),
               args.pWidget.on("formExecutedButNotSaved", lang.hitch(this, function(){
                  this.emit("formExecutedButNotSaved");
               })),
            
               args.pWidget.on("formCanceled", lang.hitch(this, function(){
                  this.emit("formCanceled");
               }))
            );
         },
         destroy: function()
         {
            this.mSignal.remove();
            this.mSignal = null;
            this.inherited(arguments);
         }
      });
   }
);
